<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="试卷编号" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入试卷编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="名称" prop="paperName">
        <el-input
          v-model="queryParams.paperName"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['paper:paper:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-popover
          ref="popover"
          placement="bottom"
          trigger="hover">
          <div style="text-align: right; margin: 0">
            <el-button type="primary" plain size="mini"  @click="handleAddPaper('dynamics')">动态组卷</el-button>
            <el-button type="primary" plain size="mini" @click="handleAddPaper('random')">抽题组卷</el-button>
            <el-button type="primary" plain size="mini" @click="handleAddPaper('artificial')">手动组卷</el-button>
          </div>
        </el-popover>
        <el-button  type="primary" plain icon="el-icon-plus" size="mini" v-popover:popover>新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['paper:paper:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['paper:paper:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :disabled="single"
          @click="handleExport"
          v-hasPermi="['paper:paper:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="paperList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="试卷编号" align="center" prop="id" />
      <el-table-column label="名称" align="center" prop="paperName" />
      <el-table-column label="开始时间" align="center" prop="beginTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.beginTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="时长分钟" align="center" prop="duration" />
      <el-table-column label="总分" align="center" prop="paperScore" />
      <el-table-column label="试卷类型" align="center" prop="paperType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.paper_type" :value="scope.row.paperType"/>
        </template>
      </el-table-column>
      <el-table-column label="组卷类型" align="center" prop="compose_type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.paper_compose" :value="scope.row.composeType"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.paper_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status!='1'&&scope.row.status!='2'"
            size="mini"
            type="text"
            icon="el-icon-circle-check"
            @click="changeStatus(scope.row,'1')"
            v-hasPermi="['paper:paper:remove']"
          >发布</el-button>
          <el-button v-if="scope.row.status=='1'"
            size="mini"
            type="text"
            icon="el-icon-circle-close"
            @click="changeStatus(scope.row,'2')"
            v-hasPermi="['paper:paper:remove']"
          >取消</el-button>
          <el-button v-if="scope.row.status!='1'&&scope.row.status!='2'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['paper:paper:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-copy-document"
            @click="copyPaper(scope.row)"
            v-hasPermi="['paper:paper:copy']"
          >复制</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改考试试卷对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="90%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="考试部门" prop="deptList">
              <treeselect v-model="form.deptList" prop="deptList" :options="deptOptions" :multiple="true" :normalizer="normalizer" placeholder="请选择考试部门" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="名称" prop="paperName" required>
              <el-input v-model="form.paperName" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="5">
            <el-form-item label="类型" prop="paperType" required>
            <el-select v-model="form.paperType" placeholder="请选择类型">
              <el-option
                v-for="dict in dict.type.paper_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5" v-if="form.paperType==1">
            <el-form-item label="时长(分钟)" prop="duration">
              <el-input-number v-model="form.duration" :min="1"  placeholder="请输入时长"  required/>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="总分" prop="paperScore">
              {{form.paperScore}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.paperType==0||form.paperType==1">
          <el-col :span="8">
            <el-form-item label="开始时间" prop="beginTime">
              <el-date-picker clearable
                v-model="form.beginTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker clearable
                v-model="form.endTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="阅卷人" prop="grades">
                <el-button :key="index" v-for="(grade,index) in form.gradeUsers" type="primary" plain  size="mini" @click="form.gradeUsers.splice(index,1)">{{grade.userName+'-'+grade.nickName}}<i class="el-icon-delete el-icon--right"></i></el-button>
              
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="questionGradeUsers()">添加</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :key="index"  v-for="(group,index) in form.groups">
          <el-row>
            <el-col :span="24">
              <el-form-item :label="'大题'+(index+1)+'：'" >
                <el-input v-model="group.groupName" placeholder="标题" class="question-option-content-input" required/>
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="questionAdd(index)">添加题目</el-button>
                <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="groupRemove(index)">删除</el-button>
                <el-input-number v-model="group.defaultScore" :min="0.0"  placeholder="默认分值" @change="changeDefaultScore(index)" style="margin-left:20px" required/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row >
            <el-form-item :label="'题目'+(questonIndex+1)+'：'" :key="questonIndex" v-for="(question,questonIndex) in group.questions" >
              <el-col :span="20">
                <QuestionInfo :questionType="question.questionType" :question="question"/>
              </el-col>
              <el-col :span="4">
                <el-input-number v-model="question.score" @change="changeQuestionScore()" :min="0.0" required/>
                <el-button type="danger" plain size="mini" @click="questionRemove(group.questions,questonIndex)">删除</el-button>
              </el-col>
            </el-form-item>
          </el-row>
        </el-row>
        <el-row>
          <el-col :span="24">
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
        <el-button type="success" @click="groupAdd">添加大题</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择试题" :visible.sync="openQuestion" width="80%" append-to-body>
      <el-col :span="20" :xs="24">
        <el-form :model="queryQuestionParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="标题" prop="title">
            <el-input
              v-model="queryQuestionParams.title"
              placeholder="标题"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="题型" prop="questionType">
            <el-select  v-model="queryQuestionParams.questionType" placeholder="请选择题型" clearable>
              <el-option
                v-for="dict in dict.type.question_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuestionQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuestionQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-table ref="questionTable" v-loading="loading" :data="questionList" @select="handleSelectionQuestionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="标题" align="center" prop="title" :show-overflow-tooltip="true"/>
          <el-table-column label="最新版本号" align="center" prop="versionNo" />
          <el-table-column label="所属机构" align="center" prop="deptName" />
          <el-table-column label="题型" align="center" prop="questionTypeName" />
          <el-table-column label="题库" align="center" prop="repoName" />
          <el-table-column label="章节" align="center" prop="sectionName" />
          <el-table-column label="难度" align="center" prop="level">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.question_level" :value="scope.row.level"/>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="200">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        </el-table>
      <pagination
        v-show="totalQuestion>0"
        :total="totalQuestion"
        :page.sync="queryQuestionParams.pageNum"
        :limit.sync="queryQuestionParams.pageSize"
        @pagination="getQuestionList"
      />
    </el-dialog>
    <el-dialog :visible.sync="openUser" width="60%" append-to-body>
      <el-col :span="20" :xs="24">
        <el-form :model="queryUserParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="姓名" prop="userName">
            <el-input
              v-model="queryUserParams.userName"
              placeholder="姓名"
              clearable
              @keyup.enter.native="handleUserQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleUserQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetUserQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-table  ref="userTable"  v-loading="loading" :data="userList" @select="handleSelectioUserChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="用户编号" align="center" key="userId" prop="userId" />
          <el-table-column label="用户名称" align="center" key="userName" prop="userName" :show-overflow-tooltip="true" />
          <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName" :show-overflow-tooltip="true" />
          <el-table-column label="部门" align="center" key="deptName" prop="dept.deptName" :show-overflow-tooltip="true" />
          <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" width="120" />
        </el-table>
        <pagination
        v-show="totalUser>0"
        :total="totalUser"
        :page.sync="queryUserParams.pageNum"
        :limit.sync="queryUserParams.pageSize"
        @pagination="getUserList"
      />
    </el-dialog>
    <el-dialog
      title="导出结果"
      :visible.sync="exportDialogVisible"
      width="40%">
      <span v-html="exportResult"></span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="exportDialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listPaper, getPaper, delPaper, createPaper, updatePaper, editPaper, exportPapers,exportMonitor,copyPaper } from "@/api/paper/paper";
import { listQuestion, getQuestion } from "@/api/paper/question";
import {  deptTreeSelect } from "@/api/system/user";
import {  allocatedUserList } from "@/api/system/role";
import { listDept } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import QuestionInfo from "../question/questionInfo";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Paper",
  components: { Treeselect,QuestionInfo },
  dicts: ['question_type','paper_status','paper_type','question_level','paper_compose'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 试题数
      totalQuestion: 0,
      //用户数
      totalUser: 0,
      // 考试试卷表格数据
      paperList: [],
      groups: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openQuestion: false,
      openUser: false,
      // 部门树选项
      deptOptions: [],      
      // 试题表格数据
      questionList: [],
      // 用户表格数据
      userList: [],
      //当前组index
      groupIndex: 0,
      exportDialogVisible: false,
      exportResult: '',
      timerId: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        depts: null,
        paperName: null,
        beginTime: null,
        endTime: null,
        duration: null,
        paperScore: null,
        status: null,
        paperType: null,
        composeType: null,
        grades: null,
      },
      // 查询参数
      queryQuestionParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        versionNo: null,
        questionType: null,
        repoId: null,
        sectionId: null,
        level: null,
      },
      // 查询参数
      queryUserParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        roleId: null,
      },
      // 表单参数
      form: {},
      questionForm: {},
      // 表单校验
      rules: {
        paperName: [
          { required: true, message: "试卷名称不能为空", trigger: "blur" }
        ],
        paperType: [
          { required: true, message: "试卷类型不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询考试试卷列表 */
    getList() {
      this.loading = true;
      listPaper(this.queryParams).then(response => {
        this.paperList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getQuestionList() {
      this.loading = true;
      listQuestion(this.queryQuestionParams).then(response => {
        this.questionList = response.rows;
        this.totalQuestion = response.total;
        this.loading = false;
        this.$nextTick(()=>{
          this.questionList.forEach(row=>{
            this.form.groups.forEach(group=>{
              group.questions.forEach(question=>{
                if(question.id==row.id){
                  this.$refs.questionTable.toggleRowSelection(row,true);
                }
              })
            })
          });
        });      
      });
    },
    getUserList() {
      this.loading = true;
      this.queryUserParams.roleId = 2;
      allocatedUserList(this.queryUserParams).then(response => {
        this.userList = response.rows;
        this.totalUser = response.total;
        this.loading = false;
        this.$nextTick(()=>{multiple
          this.userList.forEach(row=>{
            this.form.gradeUsers.forEach(grade=>{
              if(grade.userId==row.userId){
                this.$refs.userTable.toggleRowSelection(row,true);
              }
          })
          });
        });      
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deptId: null,
        depts: null,
        deptList: [],
        groups: [{ groupName:"2",questions: []}],
        gradeUsers: [],
        paperName: null,
        beginTime: null,
        endTime: null,
        duration: null,
        paperScore: null,
        status: null,
        paperType: null,
        composeType: null,
        grades: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleQuestionQuery() {
      this.queryQuestionParams.pageNum = 1;
      this.getQuestionList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 重置按钮操作 */
    resetQuestionQuery() {
      this.resetForm("queryQuestionForm");
      this.handleQuestionQuery();
    },
    /** 搜索按钮操作 */
    handleUserQuery() {
      this.queryUserParams.pageNum = 1;
      this.getUserList();
    },
    /** 重置按钮操作 */
    resetUserQuery() {
      this.resetForm("queryUserForm");
      this.handleUserQuery();
    },    
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 多选框选中数据
    handleSelectionQuestionChange(selection,row) {
      let selected = selection.length && selection.indexOf(row) !== -1;
      this.paperEditQuestion(row,selected);
    },
    // 多选框选中数据
    handleSelectioUserChange(selection,row) {
      let selected = selection.length && selection.indexOf(row) !== -1;
      let users=this.form.gradeUsers;
      if(selected){
        users.push({userId:row.userId,userName:row.userName,nickName:row.nickName});
      }else{
        users.forEach((user,index)=>{
          if(row.userId==user.userId){
            users.splice(index,1);
          }
      });
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "创建试卷";
      listDept().then(response => {
        this.deptOptions = this.handleTree(response.data, "deptId");
      });
    },
    /** 新增按钮操作 */
    handleAddPaper(composeType) {
      this.$router.push("/paper/add/" + composeType);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // this.reset();
      const id = row.id || this.ids
      listDept().then(response => {
        this.deptOptions = this.handleTree(response.data, "deptId");
      });
      getPaper(id).then(response => {
        this.form = response.data;
        if(this.form.depts){
          this.form.deptList=[];
          this.form.depts.split(",").forEach(dept=>{this.form.deptList.push(parseInt(dept))});
        }
        if(!this.form.groups){
          this.form.groups=[{ groupName:'2'}];
        }
        if(!this.form.grades){
          this.form.gradeUsers = [];
        }
        this.open = true;
        this.title = "编辑试卷";
      });     
    },
    // 修改考试状态
    changeStatus(row,status){
      const id = row.id || this.ids
      editPaper({id:id,status:status}).then(response => {
        this.getList();
      });
    },
    // 复制试卷
    copyPaper(row){
      const id = row.id
      const that = this;
      this.$modal.confirm('是否复制试卷编号为"' + id + '"的试卷？').then(function() {
        copyPaper(id).then(response => {
          that.getList();
          that.$modal.msgSuccess("拷贝成功");
         });
      }).then(() => {
      }).catch(() => {});
    },
    changeDefaultScore(index){
      let score=0;
      this.form.groups.forEach((group,groupIndex)=>{    
         group.questions.forEach(question=>{
          if(index==groupIndex){
            question.score = group.defaultScore;
          }
          score=score+question.score;
         })
      })
      this.form.paperScore = score;
    },
    changeQuestionScore(){
      this.changeDefaultScore(-1);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let depts = ""
          this.form.deptList.forEach(dept=>{
            depts += dept+","
          })   
          if(depts.length>0){
            depts=depts.substring(0,depts.length-1)
          }
          this.form.depts = depts

          let grades = ""
          this.form.gradeUsers.forEach(grade=>{
            grades += grade.userId+","
          })   
          if(grades.length>0){
            grades=grades.substring(0,grades.length-1)
          }
          this.form.grades = grades

          if (this.form.id != null) {
            updatePaper(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            createPaper(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除考试试卷编号为"' + ids + '"的数据项？').then(function() {
        return delPaper(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      if(this.multiple){
        this.$modal.msgError('未勾选需要导出的考试！')
      }else{
        const ids = this.ids;
        const that = this;
        exportPapers(ids).then(response => {
          that.timerId = setTimeout(function () {
          that.exportMonitorResult(response.msg)
        }, 1000);
        });
      }
      // this.download('paper/paper/export', {
      //   ...this.queryParams
      // }, `paper_${new Date().getTime()}.xlsx`)
    },
    exportMonitorResult(uuid){
      exportMonitor(uuid).then(response => {
        this.exportResult = "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.data.result + "</div>";
        if(response.data.status=="1"){
          clearInterval(this.timerId)
          this.download('/paper/paper/downLoadExport/' + uuid, {}, `exam_${new Date().getTime()}.zip`)
        }
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    treeSelectDeselect(raw) {
      console.log(raw, 'deselect-->>'+raw.deptId);
      let deptList=this.form.deptList;
      deptList.forEach((dept,index)=>{
        if(dept==raw.deptId){
          deptList.splice(index,1);
        }
      })  
    },
    // 添加标题
    groupAdd() {
      let groups = this.form.groups;
      console.log(groups)
      if(groups!=undefined){
        groups.push({ groupName:'1',questions: []});
      }else{
        this.form.groups=[{ groupName:'2',questions: []}];
      }
    },
    groupRemove(index){
      this.form.groups.splice(index,1)
    },
    questionAdd(index){
      this.openQuestion = true;
      this.getQuestionList();
      this.groupIndex = index;
    },
    questionGradeUsers(){
      this.openUser = true;
      this.getUserList();
    },
    questionRemove(questions,index){
      questions.splice(index,1)
    },
    /** 添加或删除试题 */
    paperEditQuestion(row,selected) {
      const id = row.id || this.ids
      let groups=this.form.groups;
      if(selected){
        getQuestion(id).then(response => {
          let quesion = response.data;
          if(quesion.questionType=="0"||quesion.questionType=="1"){
            quesion.options.forEach(item=>{
                  //item.checked=item.answerFlag=="1"
                })
          }
          if(quesion.questionType=="8"||quesion.questionType=="9"){
            quesion.questions.forEach(qustion=>{
                qustion.options.forEach(option=>{
                 // option.checked=option.answerFlag=="1"
                })
            })
          }
          if(quesion.questionType=="10"){
            quesion.answerFlag=quesion.answerFlag+""
          }
          groups.forEach((group,index)=>{
            if(index==this.groupIndex){
              group.questions.push(quesion)
            }
          })  
        });
      }else{
        groups.forEach(group=>{
          group.questions.forEach((question,index)=>{
            if(question.id==id){
              group.questions.splice(index,1);
            }
          });
        });  
      }
    },     
  }
};
</script>
